<template>
    <div>
        <el-card>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>内容管理</el-breadcrumb-item>
                <el-breadcrumb-item>文章列表</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="btnBox">
                <div>
                    <el-button size="small" @click="addHandle">添加</el-button>
                    <el-button size="small" icon="el-icon-upload2" @click="handle('up', 'top')">上线</el-button>
                    <el-button size="small" icon="el-icon-download" @click="handle('down', 'top')">下线</el-button>
                </div>
            </div>
            <el-table :data="tableData" border style="width: 100%" height="626" @selection-change="selectChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="baikeId" label="序号" width="60"></el-table-column>
                <el-table-column label="封面图" width="130">
                    <template slot-scope="prop">
                        <el-image :src="prop.row.baikeImg" class="image-control"
                            :previewSrcList="[prop.row.baikeImg]"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="内容图" width="130">
                    <template slot-scope="prop">
                        <el-image :src="prop.row.baikeContent" class="image-control"
                            :previewSrcList="[prop.row.baikeContent]"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="baikeTitle" label="标题" show-overflow-tooltip></el-table-column>
                <el-table-column prop="baikeSubtitle" label="副标题" show-overflow-tooltip></el-table-column>
                <el-table-column label="关联商品">
                    <template slot-scope="prop">
                        {{ prop.row.productId | getProName }}
                    </template>
                </el-table-column>
                <el-table-column label="分类">
                    <template slot-scope="prop">
                        {{ prop.row.categoryId | getCateName }}
                    </template>
                </el-table-column>
                <el-table-column prop="priseNum" label="点赞数"></el-table-column>
                <el-table-column prop="collectionNum" label="收藏数"></el-table-column>
                <el-table-column prop="commentNum" label="评论数"></el-table-column>
                <el-table-column prop="isTop" label="排序"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-tag size="small" v-if="scope.row.baikeStatus == '1'">已上线</el-tag>
                        <el-tag size="small" type="warning" v-else>已下线</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" icon="el-icon-tickets"
                            @click="handle('sort', 'table', scope.row, 1)">排序</el-button>
                        <el-button size="small" icon="el-icon-upload2" v-if="scope.row.baikeStatus == '0'"
                            @click="handle('up', 'table', scope.row)">上线</el-button>
                        <el-button size="small" icon="el-icon-download" @click="handle('down', 'table', scope.row)"
                            v-if="scope.row.baikeStatus == '1'">下线</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="paginationBox">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageNum" :page-sizes="[50, 100, 200]" :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="totalNum"></el-pagination>
            </div>
        </el-card>

        <!-- 添加弹窗 -->
        <el-dialog title="添加文章" :visible.sync="addialogVisible" width="40%" top="5vh" :before-close="closeAddDialog">
            <el-form :model="form" :inline="true" :rules="rules" ref="form" label-width="120px">
                <el-form-item label="主标题" prop="baikeTitle">
                    <el-input size="small" v-model="form.baikeTitle" placeholder="请输入主标题"></el-input>
                </el-form-item>
                <el-form-item label="副标题" prop="baikeSubtitle">
                    <el-input size="small" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }"
                        v-model="form.baikeSubtitle" placeholder="请输入副标题" style="width: 300px;"></el-input>
                </el-form-item>
                <el-form-item label="文章分类">
                    <el-select v-model="form.categoryId" placeholder="请选择文章分类" size="small" style="width: 194px;"
                        @change="selectCate">
                        <el-option :label="item.categoryName" :value='item.categoryId' v-for="(item, index) in cateList"
                            :key="index"> </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否关联商品" prop="isHavePro">
                    <el-radio-group v-model="form.isHavePro">
                        <el-radio label="1">关联</el-radio>
                        <el-radio label="0">不关联</el-radio>
                    </el-radio-group>
                </el-form-item>
                <br>
                <el-form-item label="关联商品" v-show="form.isHavePro == 1">
                    <el-select v-model="form.productId" placeholder="请选择商品" size="small" style="width: 194px;">
                        <el-option :label="item.productName" :value='item.productId'
                            v-for="(item, index) in productList" :key="index"> </el-option>
                    </el-select>
                </el-form-item>
                <br>
                <el-form-item label="起始点赞数" prop="priseNum">
                    <el-input size="small" type="number" v-model="form.priseNum" placeholder="请输入副标题"></el-input>
                </el-form-item>
                <el-form-item label="起始收藏数" prop="collectionNum">
                    <el-input size="small" type="number" v-model="form.collectionNum" placeholder="请输入起始收藏数"></el-input>
                </el-form-item>
                <el-form-item label="起始评论数" prop="commentNum">
                    <el-input size="small" type="number" v-model="form.commentNum" placeholder="请输入起始评论数"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="isTop">
                    <el-input size="small" type="number" v-model="form.isTop" placeholder="数字越大，越靠前"></el-input>
                    <div class="sortTip">tips：数值越大，在列表中越靠前，最小数值为1</div>
                    <template>
                        <el-radio v-model="form.baikeStatus" label="0">下线</el-radio>
                        <el-radio v-model="form.baikeStatus" label="1">上线</el-radio>
                        <div class="sortTip">tips:选择视频或文章初始状态</div>
                    </template>
                </el-form-item>
                <br>
                <el-form-item label="封面">
                    <div class="uploadBox">
                        <div class="imgListBox" v-if="form.mainPic">
                            <div>
                                <el-image :src="form.mainPicUrl" class="avatar"
                                    :previewSrcList="[form.mainPicUrl]"></el-image>
                                <div class="closeBox" @click="delImg(0, 'mainPic')">
                                    <i class="el-icon-circle-close"></i>
                                </div>
                            </div>
                        </div>
                        <el-upload v-else action="aa" class="avatar-uploader" :on-change="proMainChange"
                            :auto-upload="false" accept=".jpg,.png" ref="addProduct_pic" :show-file-list="false">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：只能上传jpg/png文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <br>
                <el-form-item label="文章内容图片">
                    <div class="uploadBox">
                        <div class="imgListBox" v-if="form.contentImgUrl.length != 0">
                            <div v-for="(item, index) in form.contentImgUrl " :key="index">
                                <el-image :src="item" class="avatar" :previewSrcList="[item]"></el-image>
                                <div class="closeBox" @click="delImg(index, 'swiper')">
                                    <i class="el-icon-circle-close"></i>
                                </div>
                            </div>
                        </div>
                        <el-upload action="aa" class="avatar-uploader" :on-change="proSwiperChange" :auto-upload="false"
                            accept=".jpg,.png" ref="addProduct_pic" :show-file-list="false" multiple>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：只能上传jpg/png文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddDialog">取 消</el-button>
                <el-button type="primary" @click="submitAddDialog">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="排序" :visible.sync="sortDia" width="30%" :before-close="closeSortDialog">
            <el-form :model="sortForm" ref="sotrForm" label-width="120px">
                <el-form-item label="排序数值">
                    <el-input size="small" type="number" v-model="sortForm.flag" placeholder="请输入排序数值"></el-input>
                    <div class="sortTip">tips：数值越大，在列表中越靠前，最小数值为1</div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeSortDialog">取 消</el-button>
                <el-button type="primary" @click="submitSortDialog">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>

import { addTopicOrVideo, getTopicOrVideoList, updateStatus, listCategory } from '../../network/content'
import { getAllProductList } from '../../network/product'

let that

export default {
    data() {
        return {
            tableData: [{
                brandName: 1
            }],
            cateList: [],//分类列表
            addialogVisible: false,//弹窗4
            brandName: '',
            form: {
                baikeTitle: '', //主标题
                baikeSubtitle: '', // 副标题
                isHavePro: '1', // 是否管理商品
                productId: '', // 关联商品id
                categoryId: '',//分类id
                categoryName: '',
                baikeStatus: 1,  //状态
                priseNum: 0,
                collectionNum: 0,
                commentNum: 0,
                isTop: 1,
                companyId: sessionStorage.companyId,
                mainPic: '',
                mainPicUrl: '',
                contentList: [],  // 文章主图
                contentImgUrl: [], // 主图路径
            },
            rules: {
                baikeTitle: [
                    { required: true, message: '请输入主标题', trigger: 'blur' },
                ],
                baikeSubtitle: [
                    { required: true, message: '请输入副标题', trigger: 'blur' },
                ],
                categoryId: [
                    { required: true, message: '请选择文章分类', trigger: 'change' },
                ],
                isHavePro: [
                    { required: true, message: '', trigger: 'change' },
                ],
                priseNum: [
                    { required: true, message: '请输入起始点赞数', trigger: 'blur' },
                ],
                collectionNum: [
                    { required: true, message: '请输入起始收藏数', trigger: 'blur' },
                ],
                commentNum: [
                    { required: true, message: '请输入起始评论数', trigger: 'blur' },
                ],
            },
            selectList: [],// 选择的视频
            productList: [],
            videoDia: false,// 视频播放弹窗
            pageSize: 50,
            pageNum: 1,
            totalNum: 0,
            sortDia: false,
            sortForm: {
                ids: '',
                status: 0,
                flag: 1,
            }
        };
    },
    methods: {

        closeSortDialog() {
            this.sortDia = false
            this.$refs.sotrForm.resetFields()
        },

        submitSortDialog() {
            this.$refs.sotrForm.validate((valid) => {
                if (!valid) return
                var form = this.sortForm;

                if (form.flag == '') {
                    this.$message.warning('请输入排序数值')
                    return
                }


                console.log(form);
                // return
                updateStatus(form).then(res => {
                    if (res.flag) {
                        this.$message.success('操作成功')
                        this.getList()
                        this.closeSortDialog()
                    } else {
                        this.$message.warning('操作失败')
                    }
                })


                console.log(form);

            });

        },

        addHandle() {
            this.addialogVisible = true
        },

        getList() {
            getTopicOrVideoList({
                companyId: sessionStorage.companyId,
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                flag: 0,
            }).then(res => {
                if (res.flag) {
                    this.tableData = res.data.list
                    this.totalNum = res.data.total
                    console.log(res);
                }
            })
        },

        handle(flag, position, obj, num) {
            if (position == 'top' && this.selectList.length == 0) {
                this.$message.warning('请选择要操作的数据')
                return
            }
            if (position == 'top') {
                var ids = '';
                this.selectList.forEach(ele => {
                    ids += ele.baikeId + ','
                })
                updateStatus({
                    ids,
                    status: flag == 'up' ? 1 : 0,
                    flag: 0
                }).then(res => {
                    if (res.flag) {
                        this.$message.success('操作成功')
                        this.getList()
                    } else {
                        this.$message.warning('操作失败')
                    }
                })
            } else {
                var sendForm = {
                    ids: obj.baikeId,
                    status: '',
                    flag: ''
                }
                if (flag == 'sort') {
                    // 置顶
                    this.sortForm.ids = obj.baikeId
                    this.sortForm.flag = obj.isTop
                    this.sortDia = true
                } else {
                    // 上架 下架
                    sendForm.status = flag == 'up' ? 1 : 0
                    sendForm.flag = 0
                    updateStatus(sendForm).then(res => {
                        if (res.flag) {
                            this.$message.success('操作成功')
                            this.getList()
                        } else {
                            this.$message.warning('操作失败')
                        }
                    })
                }

            }
        },
        selectChange(val) {
            this.selectList = val
        },

        submitAddDialog() {

            this.$refs.form.validate((valid) => {
                if (!valid) return
                var form = this.form;

                if (form.isHavePro == 1 && form.productId == '') {
                    this.$message.warning('请选择关联商品')
                    return
                }

                if (form.mainPic == '') {
                    this.$message.warning('请上传封面')
                    return
                }
                if (form.contentImgUrl.length == 0) {
                    this.$message.warning('请上传文章内容图片')
                    return
                }

                let fd = new FormData();


                fd.append("baikeTitle", form.baikeTitle);
                fd.append("baikeType", 0);
                fd.append("productId", form.productId);
                fd.append("baikeSubtitle", form.baikeSubtitle);
                fd.append("priseNum", form.priseNum);
                fd.append("collectionNum", form.collectionNum);
                fd.append("commentNum", form.commentNum);
                fd.append("baikeStatus", form.baikeStatus);
                fd.append("categoryId", form.categoryId);
                fd.append("categoryName", form.categoryName);
                fd.append("companyId", form.companyId);
                fd.append("isTop", form.isTop);


                // 主图
                fd.append("mainImg", form.mainPic);
                // 内容
                form.contentList.forEach(ele => {
                    fd.append("content", ele);
                })


                addTopicOrVideo(fd).then(res => {
                    if (res.flag) {
                        this.$message.success('添加成功')
                        this.getList()
                        this.closeAddDialog()
                    } else {
                        this.$message.warning('添加失败')
                    }
                })


                console.log(form);

            });

        },

        selectCate() {
            this.cateList.forEach(ele => {
                if (ele.categoryId == this.form.categoryId) {
                    this.form.categoryName = ele.categoryName
                }
            })
        },
        // 关闭弹窗
        closeAddDialog() {
            this.addialogVisible = false
            this.$refs.form.resetFields();

            this.form.mainPic = ''
            this.form.mainPicUrl = ''
            this.form.contentImgUrl = ''
            this.form.contentList = ''
        },
        // 上传封面
        proMainChange(file) {
            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (
                fileType == 'jpg' ||
                fileType == 'png'
            ) {
                this.form.mainPicUrl = URL.createObjectURL(file.raw);
                this.form.mainPic = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传jpg或png文件')
                return;
            }
        },

        // 上传内容
        proSwiperChange(file, fileList) {
            console.log(file);
            console.log(fileList);
            this.form.contentList = []
            this.form.contentImgUrl = []
            fileList.forEach(item => {
                item.fileType = item.name.substring(item.name.lastIndexOf(".") + 1);
                if (
                    item.fileType == 'jpg' ||
                    item.fileType == 'png'
                ) {
                    this.form.contentList.push(item.raw)
                    this.form.contentImgUrl.push(URL.createObjectURL(item.raw))
                }
            })

            var flag = fileList.some(item => {
                return item.fileType != 'jpg' && item.fileType != 'png'
            })
            if (flag) {
                this.$message.warning('只能上传jpg或png文件')
            }

            console.log(flag);


        },


        // 删除选中的图片
        delImg(index, flag) {
            if (flag == 'swiper') {
                this.form.contentImgUrl.splice(index, 1)
                this.form.contentList.splice(index, 1)
            } else if (flag == 'mainPic') {
                this.form.mainPicUrl = ''
                this.form.mainPic = ''
            }
        },


        handleSizeChange(val) {
            this.pageSize = val;
        },
        handleCurrentChange(val) {
            this.currentPage = val;
        },

        getCateList() {
            listCategory({
                companyId: sessionStorage.companyId
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    this.cateList = res.data
                }
            })
        },
        getAllProList() {
            getAllProductList({
                companyId: sessionStorage.companyId
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    this.productList = res.data
                }
            })
        },


    },
    created() {
        that = this
        this.getList()
        this.getCateList()
        this.getAllProList()
    },
    filters: {
        getProName(val) {
            var name = '';
            that.productList.forEach(ele => {
                if (ele.productId == val) {
                    name = ele.productName
                }
            })
            return name
        },
        getCateName(val) {
            var name = '';
            that.cateList.forEach(ele => {
                if (ele.categoryId == val) {
                    name = ele.categoryName
                }
            })
            return name
        }
    },
};
</script>

<style scoped>
.video {
    width: 120px;
    height: 120px;
}

.demo-ruleForm {
    margin-top: 16px;
    height: 78vh;
    overflow-y: scroll;
}

.demo-ruleForm::-webkit-scrollbar {
    display: none;
}

.el-input {
    width: 193px;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 8px;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.imgListBox,
.uploadBox {
    display: flex;
    align-content: center;
}

.closeBox {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
    height: 20px;
    background-color: rgba(0, 0, 0, .5);
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
    z-index: 10;
}

.playBtn {
    position: absolute;
    top: 34px;
    left: 34px;
    font-size: 32px;
    color: #fff;
}

.imgListBox>div {
    position: relative;
    margin-right: 16px;
}

.el-upload__tip {
    color: red;

}

.videoBox {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}


.videoCon {
    width: 500px;
    height: 500px;
}

.formatBox {
    display: flex;
    align-items: center;
    width: 100%;

}

.formatBox>div>.el-input {
    width: 150px;
}

.formatBox>div {
    margin: 16px 0 0 16px;
    display: flex;
    align-items: center;
}

.avatar-uploader1,
.avatar-uploader-icon1,
.avatar1 {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
}

.addBtn {
    font-size: 18px;
    margin-left: 16px;
    color: #999;
    cursor: pointer;
}

.paginationBox {
    display: flex;
    align-content: center;
    justify-content: end;
    width: 100%;

}

.image-control {
    width: 100px;
    height: 100px;
}

.sortTip {
    color: #409eff;
}
</style>